package com.luhongda.music.common;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.StreamProgress;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpConnection;
import cn.hutool.http.HttpResponse;

import java.io.File;
import java.net.URLDecoder;
import java.nio.charset.Charset;

public class MyHttpResponse extends HttpResponse {

    protected MyHttpResponse(HttpConnection httpConnection, Charset charset, boolean isAsync, boolean isIgnoreBody) {
        super(httpConnection, charset, isAsync, isIgnoreBody);
    }

    public long writeBody(File destFile, StreamProgress streamProgress) {
        if (null == destFile) {
            throw new NullPointerException("[destFile] is null!");
        } else {
            if (destFile.isDirectory()) {
                String path = this.httpConnection.getUrl().getPath();
                String fileName = StrUtil.subSuf(path, path.lastIndexOf(47) + 1);
                fileName = decode(fileName);
                destFile = FileUtil.file(destFile, fileName);
            }
            return this.writeBody(FileUtil.getOutputStream(destFile), true, streamProgress);
        }
    }

    public String decode(String fileName) {
        try {
            return URLDecoder.decode(fileName, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return UUID.fastUUID().toString();
    }
}
